#ifndef __CORE_HANDLE__
#define __CORE_HANDLE__

#include <cassert>

namespace Core
{
	template<typename TAG>
	class CHandle
	{
		enum
		{
			MAX_BITS_INDEX = 16;
			MAX_BITS_MAGIC = 16;

			MAX_INDEX = (1 << MAX_BITS_INDEX) - 1;
			MAX_MAGIC = (1 << MAX_BITS_MAGIC) - 1;
		};

		union
		{
			struct 
			{
				unsigned int m_Index : MAX_BITS_INDEX;
				unsigned int m_Magic : MAX_BITS_MAGIC;
			};

			unsigned int m_Handle;
		};

	public:

		CHandle(void ) : m_Handle(0)
		{

		}

		void init(unsigned int index);

		unsigned int getIndex() const
		{
			return m_Index;
		}

		unsigned int getMagic() const
		{
			return m_Magic;
		}

		unsigned int getHandle() const
		{
			return m_Handle;
		}

		bool isNull() const
		{
			return m_Handle != 0;
		}

		operator unsigned int () const 
		{
			return m_Handle;
		}

		bool operator != (const CHandle& r) const
		{
			return getHandle() != r.getHandle();
		}

		bool operator == (const CHandle& r) const
		{
			return getHandle() == r.getHandle();
		}

	};


	template<typename TAG>
	void CHandle<TAG>::init(unsigned int index)
	{
		assert(isNull());
		assert(index <= MAX_INDEX);
		static unsigned int s_AutoMagic = 0;
		if (++s_AutoMagic > MAX_MAGIC)
		{
			s_AutoMagic = 1;
		}

		m_Index = index;
		m_Magic = s_AutoMagic;
	}



}




#endif
